﻿namespace S4sme.Web.Controllers
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;

    using S4sme.Domain;
    using S4sme.Tasks.Blog.ViewModels;

    using SharpLite.Domain.DataInterfaces;

    public class AuthenticationController : Controller
    {
        private readonly IRepository<User> userRepository;

        //
        // GET: /Blog/Authenticate/
        public AuthenticationController(IRepository<User> userRepository)
        {
            this.userRepository = userRepository;
        }

        public ActionResult Login(string returnUrl)
        {
            var loginAttempt = new LoginViewModel { ReturnUrl = returnUrl ?? this.Url.Action("Index", "Home") };

            return View(loginAttempt);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(LoginViewModel loginViewModel) 
        {
            var user = this.userRepository.GetAll().SingleOrDefault(u => 
                u.Username == loginViewModel.Username &&  
                u.Password == loginViewModel.Password);

            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(loginViewModel.Username, false);
                TempData["message"] = "You have successfully logged in.";
                return Redirect(loginViewModel.ReturnUrl);
            }

            ViewData["message"] = "The login credentials provided were invalid.";
            return View(loginViewModel);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            var authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, string.Empty)
            {
                Expires = DateTime.Now.AddYears(-1)
            };
            Response.Cookies.Add(authenticationCookie);

            var aspNetCookie = new HttpCookie("ASP.NET_SessionId", string.Empty)
            {
                Expires = DateTime.Now.AddYears(-1)
            };
            Response.Cookies.Add(aspNetCookie);

            return RedirectToAction("Index", "Post");
        }

    }
}
